/*
 * @Author: DESKTOP-05FP536\Administrator 18368095041@163.com
 * @Date: 2025-01-24 16:31:57
 * @LastEditors: DESKTOP-05FP536\Administrator 18368095041@163.com
 * @LastEditTime: 2025-01-26 18:01:45
 * @FilePath: \road-admin-web\src\service\useRouteHelper.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import {
    useRouter,
    type RouteLocationAsRelativeGeneric,
    type RouteLocationAsPathGeneric
} from 'vue-router';

import { replaceStringUndefined } from '@/utils';

export const useRouteHelper = () => {
    const router = useRouter();

    const currentPath = router.currentRoute.value.path;

    const query = ref<Record<string, unknown>>({});

    const routerPush = (
        route: RouteLocationAsRelativeGeneric | RouteLocationAsPathGeneric
    ) => {
        // const routeQuery: Record<string, unknown> = {};
        // if (route.query) {
        //     Reflect.ownKeys(route.query).forEach((key) => {
        //         const value = Reflect.get(route.query!, key);
        //         routeQuery[key as string] = value === undefined ? ;
        //     });
        // }
        router.push({
            ...route,
            query: {
                param: JSON.stringify(route.query, (_, value) => {
                    if (value === undefined) {
                        return 'undefined';
                    }
                    return value;
                })
            }
        });
    };

    watch(
        () => router.currentRoute.value,
        (newVal) => {
            if (
                currentPath === newVal.path &&
                typeof newVal.query.param === 'string'
            ) {
                query.value = replaceStringUndefined(
                    JSON.parse(newVal.query.param)
                ) as Record<string, unknown>;
                console.log(111, query.value);
                router.replace(newVal.path);
            }
        },
        {
            deep: true,
            immediate: true
        }
    );

    return {
        query: readonly(query),
        routerPush
    };
};
